//
//  HJRecommendController.m
//  KaiChat
//
//  Created by lx on 2024/3/11.
//

#import "HJRecommendController.h"
#import "HJRecommendInformationCell.h"
#import "HJInformationFollowCell.h"
#import "HJInformationPresent.h"
#import "HJRefreshFooter.h"
#import "HJRefreshHeader.h"
#import "HJFlutterController.h"
#import "TJEmptyDataHandler.h"
#import "HJPhotoBrowser.h"
#import "HJShareController.h"
#import "HJVideoPlayController.h"
#import "HJPopMenuController.h"
#import "HJUserHomePageController.h"
#import "HJPostInformationController.h"

@interface HJRecommendController ()<HJInformationCellDelegate>

@property (nonatomic, strong) NSMutableArray *datas;
@property (nonatomic, assign) NSInteger pageIndex;
@property (nonatomic, strong) TJEmptyDataHandler *emptyDataHandler;
@property (nonatomic, strong) NSArray *newsDatas;

@end

@implementation HJRecommendController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.pageIndex = 1;
    
    self.tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 0.1)];
    [self.tableView registerClass:HJRecommendInformationCell.class forCellReuseIdentifier:@"HJRecommendInformationCell"];
    [self.tableView registerClass:HJInformationFollowCell.class forCellReuseIdentifier:@"HJInformationFollowCell"];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.tableView setSectionIndexColor:UIColor.tj_9B9B9BColor];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(0);
        make.left.right.bottom.offset(0);
    }];

    self.tableView.mj_header = [HJRefreshHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    self.tableView.mj_footer = [HJRefreshFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    self.tableView.mj_footer.hidden = YES;
    self.tableView.mj_header.hidden = YES;

    _emptyDataHandler = [TJEmptyDataHandler emptyDataHandleWithScrollView:self.tableView];
    
    if (self.type == 2) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handlePostNewsSucceedNotification) name:postNewsSucceedNotification object:nil];
    }
    
    if (self.type == 2) {
        UIButton *addButton = [UIButton addToView:self.view];
        [addButton addTarget:self action:@selector(didClickAddButton) forControlEvents:UIControlEventTouchUpInside];
        [addButton setImage:[UIImage imageNamed:@"addInformation"] forState:UIControlStateNormal];
        [addButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.inset(leftRightMargin);
            make.width.height.offset(58);
            make.bottom.inset(20);
        }];
    }
}

- (void)loadData {
    if (_datas.count == 0) {
        [self showLoading];
        [self loadNewData];
    }
}

- (void)didClickAddButton {
    [HJPostInformationController showInController:self];
}

- (void)handlePostNewsSucceedNotification {
    [self loadNewData];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.datas.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    HJInformationLayout *layout = self.datas[indexPath.row];
    if (layout.isFollow) {
        HJInformationFollowCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HJInformationFollowCell" forIndexPath:indexPath];
        cell.layout = layout;
        cell.delegate = self;
        return cell;
    }
    HJRecommendInformationCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HJRecommendInformationCell" forIndexPath:indexPath];
    cell.delegate = self;
    cell.layout = layout;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    HJInformationLayout *layout = self.datas[indexPath.row];
    if (layout.isFollow) return;
    
    HJFlutterController *flutterController = [[HJFlutterController alloc] initWithName:HJFlutterPageNews];
    flutterController.arguments = @{
        @"type": @(self.type),
        @"id": layout.model.informationId
    };
    [self.navigationController pushViewController:flutterController];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    HJInformationLayout *model = self.datas[indexPath.row];
    return model.height;
}

- (void)informationCellDidClickFollowButton:(HJInformationFollowCell *)cell followCell:(HJFollowCell *)followCell {
    [HJHUD showGraceTimeLoadingInView:self.view];
    
    [HJInformationPresent followUser:followCell.model.userId complete:^(NSError * _Nullable error) {
        if (!error) {
            [HJHUD hiddenLoadingInView:self.view];
            followCell.model.isFollow = !followCell.model.isFollow;
            followCell.model = followCell.model;
            
            if (followCell.model.isFollow) {
                [HJHUD showSucceedMessage:@"Follow the success"];
                if (!self.newsDatas) {
                    [self loadNewData];
                }
            } else {
                [HJHUD showMessage:@"unfollow"];
            }
        }
    }];
    
}


- (void)informationCellDidClickFollowCell:(HJInformationFollowCell *)cell followCell:(HJFollowCell *)followCell indexPath:(NSIndexPath *)indexPath {
    HJInformationLayout *layout = self.datas.firstObject;
    HJFollowModel *followModel = layout.followDatas[indexPath.row];
    
    HJUserHomePageController *userHomePageController = [[HJUserHomePageController alloc] init];
    userHomePageController.userId = followModel.userId;
    userHomePageController.nickName = followModel.nickname;
    [userHomePageController setFollowStateChanageBlock:^(BOOL isFollow) {
        followModel.isFollow = isFollow;
        NSLog(@"followModel.isFollow = %d", followModel.isFollow);
        followCell.model = followModel;
    }];
    
    [[HJTools currentNavController] pushViewController:userHomePageController];
}

- (void)informationCellDidClickFoldButton:(HJInformationFollowCell *)cell foldButton:(UIButton *)foldButton {
    
    if (cell.layout.isFollow) {
        cell.layout.isFold = !cell.layout.isFold;
        if (cell.layout.isFold) {
            cell.layout.height = 50;
        } else {
            cell.layout.height = 50 + cell.layout.followDatas.count * 60;
        }
        [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
        
        dispatch_async_sql_queue(^{
            HJUserModel *userModel = HJUserModel.currentAccountModel;
            userModel.isRecommendFollowFold = cell.layout.isFold;
            [userModel bg_saveOrUpdate];
        });
    } else {
        HJInformationLayout *layout = cell.layout;
        layout.isFold = !layout.isFold;
        [layout calculateLayout];
        NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
        [UIView setAnimationsEnabled:NO];
        [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
        [UIView setAnimationsEnabled:YES];
    }
}

- (void)informationCellDidClickImageView:(HJRecommendInformationCell *)cell imageView:(UIImageView *)imageView index:(NSInteger)index {
    
    if (cell.layout.isVideo) {
        HJVideoPlayController *videoPlayController = [[HJVideoPlayController alloc] init];
        videoPlayController.url = cell.layout.mediaDatas.firstObject;
        [self presentViewController:videoPlayController animated:YES completion:nil];
        return;
    }
    
    NSMutableArray *Marr = [NSMutableArray array];
    [cell.layout.model.images enumerateObjectsUsingBlock:^(NSString *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        HJPhotoItem *item = [[HJPhotoItem alloc] init];
        item.thumbUrl = obj;
        item.originalUrl = obj;
        if (idx == index) {
            item.sourceView = imageView;
            item.thumbImage = imageView.image;
        }
        [Marr addObject:item];
    }];
    HJPhotoBrowser *browser = [HJPhotoBrowser browserWithPhotoItems:Marr selectedIndex:index];
    [browser showFromViewController:self];
}


- (void)informationCellDidClickTapAvatarImageView:(HJRecommendInformationCell *)cell {
    HJInformationModel *model = cell.layout.model;
    HJUserHomePageController *userHomePageController = [[HJUserHomePageController alloc] init];
    userHomePageController.userId = model.userId;
    userHomePageController.nickName = model.nickname;
    [[HJTools currentNavController] pushViewController:userHomePageController];
}

- (void)informationCellDidClickMoreButton:(HJRecommendInformationCell *)cell button:(UIButton *)button {
    
    HJInformationModel *model = cell.layout.model;
    
    NSMutableArray *types = [NSMutableArray array];
    if (model.isSelf) {
        [types addObject:@(HJPopMenuTypeNewsDelete)];
    } else {
        if (model.is_follow) {
            [types addObject:@(HJPopMenuTypeNewsUnFollow)];
        } else {
            [types addObject:@(HJPopMenuTypeNewsFollow)];
        }
        [types addObject:@(HJPopMenuTypeNewsHiden)];
    }
    
    HJPopMenuController *popMenuController = [[HJPopMenuController alloc] initWithTypes:types];
    popMenuController.controllerName = NSStringFromClass(self.class);
    popMenuController.sourceRect = [button.superview convertRect:button.frame toView:getMainWindow()];
    [popMenuController showInController:self];
    TJWeakify(self)
    [popMenuController setDidSelectItemBlock:^(HJPopMenuType type) {
        if (type == HJPopMenuTypeNewsDelete) {
            [HJInformationPresent deletePostDataWithNewsId:model.informationId complete:^(NSError * _Nullable error) {
                if (!error) {
                    [weakself.datas removeObject:cell.layout];
                    if (weakself.datas.count == 0) {
                        [weakself.tableView reloadData];
                    } else {
                        NSIndexPath *indexPath = [weakself.tableView indexPathForCell:cell];
                        [weakself.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
                    }
                }
            }];
            return;
        }
        
        if (type == HJPopMenuTypeNewsFollow || type == HJPopMenuTypeNewsUnFollow) {
            [HJInformationPresent followUser:model.userId complete:^(NSError * _Nullable error) {
                if (!error) {
                    model.is_follow = !model.is_follow;
                    cell.layout = cell.layout;
                    
                    if (cell.layout.model.is_follow) {
                        [HJHUD showSucceedMessage:@"Follow the success"];
                    } else {
                        [HJHUD showMessage:@"unfollow"];
                    }
                    
                    //修改所有数据源的关注
                    for (HJInformationLayout *obj in self.datas) {
                        if ([obj.model.userId isEqualToString:model.userId]) {
                            obj.model.is_follow = model.is_follow;
                        }
                    }
                }
            }];
            return;
        }
        
        if (type == HJPopMenuTypeNewsHiden) {
            [HJInformationPresent hidePostDataWithNewsId:model.informationId complete:^(NSError * _Nullable error) {
                if (!error) {
                    [weakself.datas removeObject:cell.layout];
                    if (weakself.datas.count == 0) {
                        [weakself.tableView reloadData];
                    } else {
                        NSIndexPath *indexPath = [weakself.tableView indexPathForCell:cell];
                        [weakself.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
                    }
                }
            }];
            return;
        }
    }];
}

- (NSMutableArray *)datas {
    if (!_datas) {
        _datas = [NSMutableArray array];
    }
    return _datas;
}

- (NSArray *)getDatas {
    return self.datas;
}

- (void)refreshRecommendData {
    [HJInformationPresent loadRecommendUsersDataComplete:^(NSArray<HJFollowModel *> * _Nullable recommendList) {
        HJInformationLayout *layout = self.datas.firstObject;
        if (layout.isFollow) {
            [self.datas removeObject:layout];
            if (recommendList.count) {
                [self.datas insertObject:[HJInformationLayout followLayoutWithDatas:recommendList] atIndex:0];
            }
            [self.tableView reloadData];
        }
    }];
}

- (void)loadNewData {
    
    self.pageIndex = 1;
    [self.tableView.mj_footer resetNoMoreData];
    
    [HJInformationPresent loadNewsListWithType:self.type newsTypeId:self.newsTypeId tags:nil pageIndex:self.pageIndex complete:^(NSInteger serverPageSize, NSArray<HJInformationModel *> * _Nullable news, NSArray <HJFollowModel *>* _Nullable recommendUsers, NSError * _Nullable error) {
 
        
        self.newsDatas = news;
        [self hiddenLoading];
        [self.datas removeAllObjects];
        [self.tableView.mj_header endRefreshing];
        self.pageIndex = 2;
        self.emptyDataHandler.canDisplay = YES;
        self.tableView.mj_header.hidden = NO;

        if (news.count) {
            self.tableView.mj_footer.hidden = NO;
        }
        
        if (news.count < serverPageSize) {
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
        }
        
        for (HJInformationModel *model in news) {
            [self.datas addObject:[HJInformationLayout layoutWithModel:model]];
        }
        
        dispatch_async_sql_queue(^{
            BOOL isRecommendFollowFold = HJUserModel.currentAccountModel.isRecommendFollowFold;
            if (recommendUsers.count) {
                HJInformationLayout *firstLayout =  [HJInformationLayout followLayoutWithDatas:recommendUsers];
                firstLayout.isFold = isRecommendFollowFold;
                if (firstLayout.isFold) {
                    firstLayout.height = 50;
                } else {
                    firstLayout.height = 50 + firstLayout.followDatas.count * 60;
                }
                [self.datas insertObject:firstLayout atIndex:0];
            }
            dispatch_async_main_queue(^{
                [self.tableView reloadData];
            });
        });
    }];
    
}

- (void)loadMoreData {
    [HJInformationPresent loadNewsListWithType:self.type newsTypeId:self.newsTypeId tags:nil pageIndex:self.pageIndex complete:^(NSInteger serverPageSize, NSArray<HJInformationModel *> * _Nullable news, NSArray <HJFollowModel *>* _Nullable recommendUsers, NSError * _Nullable error) {
        
        [self.tableView.mj_footer endRefreshing];

        if (error) {
            return;
        }
        
        if (news.count < serverPageSize) {
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
        }
        
        self.pageIndex++;
        
        if (news.count) {
            NSMutableArray *datas = [NSMutableArray array];
            for (HJInformationModel *model in news) {
                [datas addObject:[HJInformationLayout layoutWithModel:model]];
            }
            [self.datas addObjectsFromArray:datas];
        }
 
        [self.tableView reloadData];
    }];
}

- (void)dealloc {
    if (self.type == 2) {
        [[NSNotificationCenter defaultCenter] removeObserver:self];
    }
}

@end
